import { Draw, Snap } from 'ol/interaction';
import { createBox, createRegularPolygon } from 'ol/interaction/Draw';
import { Tile as TileLayer, Vector as VectorLayer } from 'ol/layer';
import { Vector as VectorSource } from 'ol/source';
import { LineString, Point, Polygon, Circle as CircleGeometry } from 'ol/geom';

import * as turf from '@turf/turf';
function DrawVector(map) {
    this.map = map;
    this.vectorSource = new VectorSource();
    // this.vectorLayer = new VectorLayer({
    //     source: this.vectorSource
    // });
    // this.map.addLayer(this.vectorLayer);
    this.drawInteraction = null;
    this.snapInteraction = new Snap({ source: this.vectorSource });
    this.map.addInteraction(this.snapInteraction);
    this.features = [];
    this.continuous = false;
    this.onDrawEndCallbacks; // 用于存储绘制结束后的回调函数
}

/**
 * 开始绘制
 * @param {string} type - 绘制类型（Point, LineString, Polygon, Circle, Rectangle）
 * @param {boolean} continuous - 是否连续绘制，默认为 false
 * @param {function} onDrawEnd - 绘制结束后回调函数，返回绘制的坐标
 */
DrawVector.prototype.startDrawing = function (type, continuous = false, onDrawEnd, circlePointNumber) {
    this.continuous = continuous;
    if (onDrawEnd) {
        this.onDrawEndCallbacks = onDrawEnd;
    }
    this.drawInteraction = new Draw({
        source: this.vectorSource,
        type: type === 'Rectangle' ? 'Circle' : type, // 使用 Circle 类型，createBox 会将其转换为矩形
        geometryFunction: getGeometryFunction(type, circlePointNumber) //获取绘制方法
    });
    this.map.addInteraction(this.drawInteraction);
    this.drawInteraction.on('drawend', this.handleDrawEnd.bind(this));
};

function getGeometryFunction(type, circlePointNumber) {
    switch (type) {
        case 'Rectangle':
            return createBox(); // 返回一个函数
        case 'Circle':
            return createRegularPolygon(circlePointNumber || 40); // 假设有一个 createCircle 函数
        default:
            return undefined;
    }
}

/**
 * 处理绘制结束
 * @param {Event} event - 绘制结束事件
 */
DrawVector.prototype.handleDrawEnd = function (event) {
    const feature = event.feature;
    if (this.continuous) {
        this.features = [feature];
        // this.vectorSource.addFeature(feature);
    } else {
        this.features = [feature];
        this.map.removeInteraction(this.drawInteraction);
    }

    // 调用绘制结束后的回调函数
    this.onDrawEndCallbacks(this.getCoordinates());
};

/**
 * 获取绘制的坐标
 * @returns {Array} 绘制的坐标数组
 */
DrawVector.prototype.getCoordinates = function () {
    return this.features.map((feature) => {
        const geometry = feature.getGeometry();
        if (geometry instanceof Point) {
            return geometry.getCoordinates();
        } else if (geometry instanceof LineString) {
            return geometry.getCoordinates().map((coord) => coord);
        } else if (geometry instanceof Polygon) {
            return geometry.getCoordinates()[0].map((coord) => coord);
        } else if (geometry instanceof CircleGeometry) {
            return {
                center: geometry.getCenter(),
                radius: geometry.getRadius()
            };
        }
    });
};

/**
 * 取消绘制
 */
DrawVector.prototype.cancelDrawing = function () {
    this.map.removeInteraction(this.drawInteraction);
    this.features = [];
    this.vectorSource.clear();
};

//计算点和线的缓冲区，返回缓冲区坐标
DrawVector.prototype.createBuffer = function (coordinates, radiusMeters, geometryType = 'Point') {
    // 定义地理坐标系的单位转换（米 -> 度）
    const earthRadius = 6371000; // 地球半径，单位：米
    const degreesPerMeter = 1 / ((earthRadius * Math.PI) / 180);

    // 将半径从米转换为度
    const radiusDegrees = radiusMeters * degreesPerMeter;

    let geometry;
    if (geometryType === 'Point') {
        // 创建点几何
        geometry = turf.point(coordinates);
    } else if (geometryType === 'LineString') {
        // 创建线几何
        geometry = turf.lineString(coordinates);
    } else {
        throw new Error('geometryType must be "point" or "line"');
    }

    // 计算缓冲区
    const buffer = turf.buffer(geometry, radiusDegrees, { units: 'degrees' });

    // 提取缓冲区的坐标数组
    const bufferCoordinates = buffer.geometry.coordinates;

    return bufferCoordinates;
};

export default DrawVector;
